package cn.cuilan.filter;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 接口请求字符过滤器
 *
 * @author zhang.yan
 */
@WebFilter(filterName = "charsetFilter", urlPatterns = "/*")
public class CharsetFilter implements Filter {

    private final static Logger logger = LoggerFactory.getLogger(CharsetFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (logger.isDebugEnabled()) {
            logger.debug("CharsetFilter is init! [filterName: charsetFilter, urlPatterns: /* ]");
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("UTF-8");
        // 设置响应头为JSON格式
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        if (logger.isDebugEnabled()) {
            logger.debug("CharsetFilter is destroy!");
        }
    }
}
